from django.contrib.auth.hashers import make_password, check_password
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http.response import HttpResponse
from .Serializer import *
import uuid
import random
import redis
import requests
from myutils.captcha.captcha import captcha
from myutils.sen_sms import send_message
from myutils.common import make_token, check_token
from myutils.user_util import PhoneBackend
from django.contrib.auth import authenticate

# Create your views here.


r2 = redis.Redis(db=2, password=123, decode_responses=True)


class UserView(APIView):
    # 同名验证
    def get(self, request):
        username = request.GET.get('username')
        set = UserModel.objects.filter(username=username)
        if set:
            return Response({'msg': '用户已存在', 'code': 400})
        return Response({'msg': '用户名可用', 'code': 200})

    # 用户注册
    def post(self, request):
        data = request.data
        data['password'] = make_password(data['password'])
        ser = UserSer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '注册成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '注册失败', 'code': 400})

    # 用户登录
    def put(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = authenticate(username=username, password=password)
        if user:
            token = make_token(user.id)
            return Response({'msg': '登录成功', 'name': user.username, 'token': token, 'code': 200})
        else:
            return Response({'msg': '登录失败', 'code': 400})
        # ser = UserModel.objects.filter(username=username).first()
        # if not ser:
        #     return Response({'msg': '没有该用户, 请先注册', 'code': 400})
        #
        # if check_password(password, ser.password):
        #     token = make_token(ser.id)
        #     return Response({'msg': '登录成功', 'token': token, 'code': 200})
        # else:
        #     return Response({'msg': '密码错误', 'code': 400})


class Uuid(APIView):
    # 获取uuid
    def get(self, request):
        uuid_code = uuid.uuid4()
        return Response({'msg': 'OK', 'uuid_code': uuid_code, 'code': 200})


class ImageView(APIView):
    # 获取图形验证码
    def get(self, request):
        image_id = request.GET.get('image_id')
        code, img = captcha.generate_captcha()
        r2.set(image_id, code, ex=300)
        return HttpResponse(img, 'image/png')

    # 校验图形验证码
    def put(self, request):
        image_id = request.data.get('image_id')
        image_code = request.data.get('image_code')
        code = r2.get(image_id)
        if code.lower() == image_code.lower():
            return Response({'msg': '验证通过', 'code': 200})
        return Response({'msg': '验证码错误', 'code': 400})


class PhoneView(APIView):
    # 校验手机号
    def get(self, request):
        phone = request.GET.get('phone')
        set = UserModel.objects.filter(phone=phone)
        if set.count() >= 1:
            return Response({'msg': '此手机号绑定已达上限', 'code': 400})
        else:
            return Response({'msg': f'此手机号还可绑定 {1 - set.count()} 个账号', 'code': 200})

    # 发送手机号验证码
    def post(self, request):
        phone = request.data.get('phone')
        phone_id = request.data.get('phone_id')
        code = '%06d' % random.randint(0, 1000000)
        ser = send_message(phone, code)
        if ser:
            r2.set(phone_id, code, ex=300)
            return Response({'msg': '发送成功', 'code': 200})
        else:
            return Response({'msg': '发送失败', 'code': 400})

    # 校验手机号验证码
    def put(self, request):
        phone_id = request.data.get('phone_id')
        phone_code = request.data.get('phone_code')
        code = r2.get(phone_id)
        if phone_code == code:
            return Response({'msg': '验证成功', 'code': 200})
        return Response({'msg': '验证码错误', 'code': 400})


# 第三方登录
class OauthView(APIView):
    def get(self, request):
        code = request.GET.get('code')
        resp = requests.post(
            url='https://api.weibo.com/oauth2/access_token',
            data={
                'client_id': '57039866',
                'client_secret': 'a73ad69c516a5676b326ba610ce9146b',
                'grant_type': 'authorization_code',
                'code': code,
                'redirect_uri': 'http://127.0.0.1:8080/oauth_callback',
            }
        ).json()
        access_token = resp.get('access_token')
        uid = resp.get('uid')
        set = OauthModel.objects.filter(uid=uid, site_type=1).first()
        if not set:
            set = OauthModel.objects.create(uid=uid, site_type=1)
        if not set.user:
            return Response({'msg': '登录成功', 'uid': uid, 'access_token': access_token, 'code': 300})
        token = make_token(set.user_id)
        return Response({'msg': '登录成功', 'name': set.user.username, 'token': token, 'access_token': access_token, 'code': 200})

    # 绑定本地账号
    def put(self, request):
        phone = request.data.get('phone')
        password = request.data.get('password')
        uid = request.data.get('uid')
        user = authenticate(username=phone, password=password)
        if not user:
            user = requests.post(
                url='127.0.0.1:8000/userapp/user',
                data={
                    'username': phone,
                    'password': make_password(password),
                    'phone': phone
                }
            ).json()
            print(user)
        set = OauthModel.objects.filter(uid=uid).first()
        if set:
            set.user_id = user.id
            set.save()
        return Response()

    # 取消授权
    def post(self, request):
        access_token = request.data.get('access_token')
        resp = requests.post(
            url='https://api.weibo.com/oauth2/revokeoauth2',
            data={
                'access_token': access_token
            }
        ).json()
        print(resp)
        return Response(resp)


class PersonalView(APIView):
    def get(self, request):
        token = request.GET.get('token')
        uid = check_token(token)['user_id']
        set = UserModel.objects.get(id=uid)
        ser = UserListSer(set).data
        return Response(ser)


class AreaView(APIView):
    def get(self, request):
        pid = request.GET.get('pid', None)
        set = AreaInfoModel.objects.filter(pid=pid)
        ser = AreaSer(set, many=True).data
        return Response(ser)


class AddressView(APIView):
    def post(self, request):
        token = request.GET.get('token')
        data = request.data
        data['user'] = check_token(token=token).get('user_id')
        ser = AddressSer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'code': 400})

    def get(self, request):
        token = request.GET.get('token')
        user_id = check_token(token=token).get('user_id')
        set = AddressModel.objects.filter(user_id=user_id)
        ser = AddressListSer(set, many=True)
        return Response(ser.data)

    def delete(self, request):
        id = request.GET.get('id')
        try:
            AddressModel.objects.get(id=id).delete()
        except BaseException as e:
            print(e)
            return Response({'msg': '删除失败', 'code': 400})
        return Response({'msg': '删除成功', 'code': 200})
